<?php

namespace App\Http\Resources;

use App\Services\TermHierarchyService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class TermCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        // 如果不需要包含子分类，使用简单的格式化
        if (!$request->boolean('include_children', false)) {
            return $this->collection->map(function ($resource) use ($request) {
                return $resource->toArray($request);
            })->toArray();
        }

        // 使用优化的层级服务构建嵌套结构
        $terms = $this->collection->toArray();
        $taxonomy = !empty($terms) ? $terms[0]['taxonomy'] : 'category';

        return TermHierarchyService::buildHierarchy($terms, $request, $taxonomy);
    }
}
